<?php

namespace app\store\controller\goods;

use app\store\controller\Controller;
use app\store\model\Category as CategoryModel;
use app\store\model\Lesson as LessonModel;
use think\Cache;

/**
 * 课程
 * Class Lesson
 * @package app\store\controller\goods
 */
class Lesson extends Controller
{
    /**
     * 课程列表
     * @return mixed
     */
    public function index()
    {
        //Cache::clear();
        $model = new LessonModel;
        $list = $model->getALL($this->request->param());
        // 商品分类
        $catgory = CategoryModel::getCacheTree();
        return $this->fetch('index', compact('list', 'catgory'));
    }

    /**
     * 删除课程
     * @param $lesson_id
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function delete($lesson_id)
    {
        $model = LessonModel::get($lesson_id);
        if (!$model->remove($lesson_id)) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    /**
     * 添加课程
     * @return array|mixed
     */
    public function add()
    {
        $model = new LessonModel;
        if (!$this->request->isAjax()) {

            $catgory = CategoryModel::getCacheTree();

            return $this->fetch('add', compact('catgory'));
        }
        // 新增记录
        if ($model->add($this->postData('lesson'))) {
            return $this->renderSuccess('添加成功', url('goods.lesson/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 编辑课程
     * @param $lesson_id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function edit($lesson_id)
    {
        //Cache::clear();
        // 模板详情
        $model = LessonModel::get($lesson_id);
        if (!$this->request->isAjax()) {
            // 获取所有地区
            $catgory = CategoryModel::getCacheTree();
            return $this->fetch('edit', compact('model', 'catgory'));
        }
        // 更新记录
        if ($model->edit($this->postData('lesson'))) {
            return $this->renderSuccess('更新成功', url('goods.lesson/index'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

}
